import type { ContributorRole, IContribution, IContributor } from './interfaces'
import { SCRIPT_CONTRIBUTORS_CONFIG } from './constants'

export class ContributorHandler {
  private static instance: ContributorHandler
  private readonly contributors: Record<string, IContributor> = SCRIPT_CONTRIBUTORS_CONFIG

  /**
   * 获取单例实例
   */
  public static getInstance(): ContributorHandler {
    if (!ContributorHandler.instance) {
      ContributorHandler.instance = new ContributorHandler()
    }
    return ContributorHandler.instance
  }

  /**
   * 获取指定贡献类型的 ID 列表
   * @param type 贡献类型
   * @returns 匹配的贡献者 ID 数组
   */
  getIdsByContributionType(type: IContribution['type']): string[] {
    return Object.entries(this.contributors)
      .filter(([_, contributor]) =>
        contributor.contributions.some(c => c.type === type) && contributor.isActive,
      )
      .map(([id]) => id)
  }

  /**
   * 获取指定 ID 的完整贡献者信息
   * @param id 贡献者 ID
   * @returns 贡献者信息或 undefined
   */
  getContributorById(id: string): IContributor | undefined {
    return this.contributors[id]
  }

  /**
   * 获取指定角色的贡献者 ID 列表
   */
  getIdsByRole(role: ContributorRole): string[] {
    return Object.keys(this.contributors).filter(
      id => this.contributors[id].roles.includes(role) && this.contributors[id].isActive,
    )
  }

  /**
   * 获取所有贡献者的分类统计
   */
  getContributionStats(): Record<IContribution['type'], number> {
    const stats: Record<string, number> = {}
    Object.values(this.contributors).forEach((contributor) => {
      if (contributor.isActive) {
        contributor.contributions.forEach((cont) => {
          stats[cont.type] = (stats[cont.type] || 0) + 1
        })
      }
    })
    return stats as Record<IContribution['type'], number>
  }
}
